<?php namespace App\Admin\Controllers;

use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

//参考https://learnku.com/articles/7670/the-use-of-wangeditor-and-laravel-in-multi-image-upload
class UploadController extends AdminController
{
    public function uploadImg(Request $request)
    {
        $file = $request->file('mypic');
        if (!empty($file)) {
            foreach ($file as $key => $value) {
                $len = $key;
            }
            if ($len > 10) {
                return response()->json(['errno' => 6, 'msg' => '最多可以上传10张图片']);
            }
            $data = [];
            for ($i = 0; $i <= $len; $i++) {
                $n = $i + 1;
                if ($file[$i]->isValid()) {
                    if (in_array(strtolower($file[$i]->extension()), ['jpeg', 'jpg', 'png'])) {
                        $name = $file[$i]->getClientOriginalName();//获取上传原文件名
                        $ext = $file[$i]->getClientOriginalExtension();//获取上传文件的后缀名
                        $filename = time() . Str::random(6) . '.' . $ext;
                        if ($file[$i]->move('../public/uploads/admin/editor/' . date('Ymd'), $filename)) {
                            $newFileName = env('APP_URL').'/uploads/admin/editor/' . date('Ymd') . '/' . $filename;
                            $data[] = $newFileName;
                            // return response()->json(['ResultData' => 0, 'info' => '上传成功', 'newFileName' => $newFileName ]);
                        }
                    } else {
                        return response()->json(['errno' => 3, 'msg' => '第' . $n . '张图片后缀名不合法!<br/>' . '只支持jpeg/jpg/png/gif格式']);
                    }
                } else {
                    return response()->json(['errno' => 1, 'msg' => '第' . $n . '张图片超过最大限制!<br/>' . '图片最大支持2M']);
                }
            }
            return response()->json(['errno' => 0, 'data' => $data]);
        } else {
            return response()->json(['error' => 5, 'msg' => '请选择文件']);
        }
    }
}
